package com.xlx.ui.service;

import com.alibaba.fastjson.JSON;
import com.xlx.ui.controller.MessageWebsocket;
import com.xlx.ui.domain.DTO.MessagQuery;
import com.xlx.ui.domain.DTO.MessageDTO;
import com.xlx.ui.domain.MO.Message;
import com.xlx.ui.domain.MO.User;
import com.xlx.ui.mapper.MessageMapper;
import com.xlx.ui.mapper.UserMapper;
import org.apache.ibatis.session.RowBounds;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.util.Sqls;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;

/**
 * @Description:
 * @author: 张川
 * @date: 2021-04-18 11:11
 */
@Service
public class MessageService {
    private MessageMapper messageMapper;
    private UserMapper userMapper;

    public MessageService(MessageMapper messageMapper, UserMapper userMapper) {
        this.messageMapper = messageMapper;
        this.userMapper = userMapper;
    }

    /**
     * 查询消息
     *
     * @param query
     * @return
     */
    public List<Message> query(MessagQuery query) {
        Example example = Example.builder(Message.class).where(Sqls.custom().andEqualTo("senduserid", query.getUserId()).andEqualTo("receive", query.getFriendsId()))
                .orWhere(Sqls.custom().andEqualTo("receive", query.getUserId()).andEqualTo("senduserid", query.getFriendsId())).orderByDesc("createtime").build();
        List<Message> messages = messageMapper.selectByExampleAndRowBounds(example, new RowBounds(query.getPage() - 1, query.getSize()));
        return messages;
    }


    /**
     * 存储消息记录
     *
     * @param message
     */
    public boolean add(Message message) {
        message.setId(null);
        int i = messageMapper.insertSelective(message);
        return i > 0;
    }

    /**
     * 转发消息
     */
    public void receive(Message message) {
        Integer receive = message.getReceive();
        MessageWebsocket.clients.forEach((s, client) -> {
            if (client.getUserId().equals(receive)) {
                client.getSession().getAsyncRemote().sendText(JSON.toJSONString(message));
            }
        });
    }


    /**
     * 清理消息
     * @param userId
     * @param receive
     * @return
     */
    public Boolean remove(Integer userId, Integer receive) {
        Example build = Example.builder(Message.class).where(Sqls.custom().andEqualTo("senduserid", userId).andEqualTo("receive", receive))
                .orWhere(Sqls.custom().andEqualTo("senduserid", receive).andEqualTo("receive", userId)).build();
        int i = messageMapper.deleteByExample(build);
        return true;
    }
}
